package com.wmz.crm.workbench.controller;

import com.wmz.crm.commons.constants.Constants;
import com.wmz.crm.commons.entity.ReturnObject;
import com.wmz.crm.commons.utils.DateFormateUtil;
import com.wmz.crm.commons.utils.HSSFUtil;
import com.wmz.crm.commons.utils.UUIDUtil;
import com.wmz.crm.settings.entity.User;
import com.wmz.crm.settings.service.UserService;
import com.wmz.crm.workbench.entity.Activity;
import com.wmz.crm.workbench.entity.ActivityRemark;
import com.wmz.crm.workbench.service.ActivityRemarkService;
import com.wmz.crm.workbench.service.ActivityService;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.lang.reflect.Field;
import java.util.*;

@Controller
public class ActivityController {
    @Autowired
    private UserService userService;

    @Autowired
    private ActivityService activityService;

    @Autowired
    private ActivityRemarkService activityRemarkService;

    @RequestMapping("/workbench/activity/index.do")
    public String index(HttpServletRequest request){
        //调用service层的方法查询所有用户
        List<User> userList = userService.queryAllUsers();
        //把数据保存到request域中
        request.setAttribute("userList",userList);
        //请求转发到市场活动的主页面
        return "workbench/activity/index";
    }

    @RequestMapping("/workbench/activity/saveCreateActivity.do")
    @ResponseBody
    public Object saveCreateActivity(Activity activity,HttpSession session){
        //获取session对象
        User user = (User) session.getAttribute(Constants.SESSION_USER);
        //封装参数
        activity.setId(UUIDUtil.getUUid());
        activity.setCreateTime(DateFormateUtil.formateDateTime(new Date()));
        activity.setCreateBy(user.getId());
        //创建响应信息对象
        ReturnObject returnObject = new ReturnObject();
        returnObject.setCode(Constants.RETURN_OBJECT_CODE_FAIL);
        try {
            int ret = activityService.saveCreateActivity(activity);
            //处理响应信息
            if(ret > 0) {
                returnObject.setCode(Constants.RETURN_OBJECT_CODE_SUCCESS);
            }else {
                returnObject.setMessage("系统忙，请稍后重试……");
            }
        }catch (Exception e) {
            e.printStackTrace();
            returnObject.setMessage("系统忙，请稍后重试……");
        }
        return returnObject;
    }

    @RequestMapping("/workbench/activity/queryActivityByConditionForPage.do")
    @ResponseBody
    public Object queryActivityByConditionForPage(String name,String owner,String startDate,
                                           String endDate,int pageNo,int pageSize){
        //封装参数
        Map<String,Object> map = new HashMap<>();
        map.put("name",name);
        map.put("owner",owner);
        map.put("startDate",startDate);
        map.put("endDate",endDate);
        map.put("beginNo",(pageNo - 1) * pageSize);
        map.put("pageSize",pageSize);
        //调用service层的方法，查询数据
        List<Activity> activityList = activityService.queryActivityByConditionForPage(map);
        int totalRow  = activityService.queryCountOfActivityByCondition(map);
        //根据查询结果，封装响应信息
        Map<String,Object> retMap = new HashMap<>();
        retMap.put("activityList",activityList);
        retMap.put("totalRows",totalRow);

        return retMap;
    }

    @RequestMapping("/workbench/activity/deleteActivityByIds.do")
    @ResponseBody
    public Object deleteActivityByIds(String[] id) {
        ReturnObject returnObject = new ReturnObject();
        returnObject.setCode(Constants.RETURN_OBJECT_CODE_SUCCESS);
        try {
            //调用service层的方法，删除市场活动
            int ret = activityService.deleteActivityByIds(id);
            if(ret<1) {
                returnObject.setCode(Constants.RETURN_OBJECT_CODE_FAIL);
                returnObject.setMessage("系统忙，请稍后重试……");
            }
        }catch (Exception e) {
            e.printStackTrace();
            returnObject.setCode(Constants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("系统忙，请稍后重试……");
        }
        return returnObject;
    }

    @RequestMapping("/workbench/activity/queryActivityById.do")
    @ResponseBody
    public Object queryActivityById(String id){
        //调用service层方法查询数据
        Activity activity = activityService.queryActivityById(id);
        return (activity!=null)?activity:null;
    }

    @RequestMapping("/workbench/activity/saveEditActivity.do")
    @ResponseBody
    public Object saveEditActivity(Activity activity,HttpSession session){
        User user = (User) session.getAttribute(Constants.SESSION_USER);
        ReturnObject returnObject = new ReturnObject();
        returnObject.setCode(Constants.RETURN_OBJECT_CODE_SUCCESS);
        //封装参数
        activity.setEditTime(DateFormateUtil.formateDateTime(new Date()));
        activity.setEditBy(user.getId());
        try {
            //调用service层方法，保存修改的市场活动
            int ret = activityService.saveEditActivtiy(activity);
            if(ret != 1) {
                returnObject.setCode(Constants.RETURN_OBJECT_CODE_FAIL);
                returnObject.setMessage("系统忙，请稍后再试……");
            }
        }catch (Exception e) {
            e.printStackTrace();
            returnObject.setCode(Constants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("系统忙，请稍后再试……");
        }
        return returnObject;
    }

    @RequestMapping("/workbench/activity/exportAllActivity.do")
    public void exportAllActivity(HttpServletResponse response) throws IOException {
        //调用service层方法，查询所有市场活动信息
        List<Activity> activities = activityService.queryAllActivity();
        //创建excel文件，把activities写入到文件中
        //创建excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        //创建工作表
        HSSFSheet sheet = wb.createSheet("市场活动列表");
        //创建行
        HSSFRow row = sheet.createRow(0);
        //创建列
        HSSFCell cell = row.createCell(0);
        //调用获取Cell函数
        getCell(row,cell,new Activity());

        //遍历activities，创建HSSRow对象，生成所有的数据行
        if(activities != null && activities.size() > 0) {
            Activity activity = null;
            for(int i=0;i<activities.size();i++){
                activity = activities.get(i);
                //每遍历出一个activity，生成一行
                row = sheet.createRow(i+1);
                //每一行创建11列，每一列的数据从activity中获取
                getCell(row,cell,activity);
            }
        }
        //根据wb对象生成excel文件
       /* OutputStream os = new FileOutputStream("D:\\activityList.xls");
        wb.write(os);
        os.close();*/
        //把生成的excel文件下载到客户端
        //设置下载类型
        response.setContentType("application/octet-stream;charset=UTF-8");
        //设置文件类型
        response.addHeader("Content-Disposition","attachment;filename=activityList.xls");
        OutputStream out = response.getOutputStream();
       /* InputStream is = new FileInputStream("D:\\activityList.xls");
        byte[] buff = new byte[256];
        int len = 0;
        while((len=is.read(buff)) != -1) {
            out.write(buff,0,len);
        }*/
        //直接把数据从wb中写入到out中；
        wb.write(out);
        //关闭资源
        wb.close();
        out.flush();
    }

    @RequestMapping("/workbench/activity/exportSelectedActivity.do")
    public void exportSelectedActivity(String[] id,HttpServletResponse response) throws IOException {
        //调用service层方法，查询所有市场活动信息
        List<Activity> activities = activityService.querySelectedActivity(id);
        //创建excel文件，把activities写入到文件中
        //创建excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        //创建工作表
        HSSFSheet sheet = wb.createSheet("市场活动列表");
        //创建行
        HSSFRow row = sheet.createRow(0);
        //创建列
        HSSFCell cell = row.createCell(0);
        getCell(row,cell,new Activity());
        //遍历activities，创建HSSRow对象，生成所有的数据行
        if(activities != null && activities.size() > 0) {
            Activity activity = null;
            for(int i=0;i<activities.size();i++){
                activity = activities.get(i);
                //每遍历出一个activity，生成一行
                row = sheet.createRow(i+1);
                //每一行创建11列，每一列的数据从activity中获取
                getCell(row,cell,activity);
            }
        }
        //把生成的excel文件下载到客户端
        //设置下载类型
        response.setContentType("application/octet-stream;charset=UTF-8");
        //设置文件类型
        response.addHeader("Content-Disposition","attachment;filename=activityList.xls");
        OutputStream out = response.getOutputStream();
        //直接把数据从wb中写入到out中；
        wb.write(out);
        //关闭资源
        wb.close();
        out.flush();
    }

    @RequestMapping("/workbench/activity/importActivity.do")
    @ResponseBody
    public Object exportActivity(MultipartFile activityFile,HttpSession session){
        User user = (User) session.getAttribute(Constants.SESSION_USER);
        ReturnObject returnObject = new ReturnObject();
        try {
            //根据excel文件生成HSSFWorkBook对象，并封装excel文件的所有信息
           HSSFWorkbook wb = new HSSFWorkbook(activityFile.getInputStream());
           //根据wb获取HSSFSheet对象，封装了一页的所有信息
            HSSFSheet sheet = wb.getSheetAt(0);
            //根据sheet获取HSSFRow对象，封装了一行的信息
            HSSFRow row =null;
            HSSFCell cell = null;
            Activity activity = null;
            List<Activity> activityList = new ArrayList<>();
            for(int i=1;i<=sheet.getLastRowNum();i++){ //sheet.getLastRowNum()：最后一行的下标
                activity = new Activity();
                row = sheet.getRow(i);
                activity.setId(UUIDUtil.getUUid());
                activity.setOwner(user.getId());
                activity.setCreateTime(DateFormateUtil.formateDateTime(new Date()));
                activity.setCreateBy(user.getId());

                for(int j=0;j<row.getLastCellNum();j++){ //row.getLastCellNum()：一行的列数
                    //根据row获取cell
                    cell = row.getCell(j);

                    //获取列中的数据
                    String cellValue = HSSFUtil.getCellValueForStr(cell);
                    if(j==0) {
                        activity.setName(cellValue);
                    }else if(j==1){
                        activity.setStartDate(cellValue);
                    }else if(j==2) {
                        activity.setEndDate(cellValue);
                    }else if(j==3) {
                        activity.setCost(cellValue);
                    }else if(j==4){
                        activity.setDescription(cellValue);
                    }
                }
                //每一行的数据封装完成之后，保存到List中
                activityList.add(activity);
            }
            //调用service层方法，保存市场活动
            int ret = activityService.saveCreateActivityByList(activityList);
            returnObject.setCode(Constants.RETURN_OBJECT_CODE_SUCCESS);
            returnObject.setRetObj("成功保存：" + ret + "条信息");
        }catch (Exception e) {
            returnObject.setCode(Constants.RETURN_OBJECT_CODE_FAIL);
            returnObject.setMessage("系统忙，请稍后重试……");
            e.printStackTrace();
        }
        return returnObject;
    }

    @RequestMapping("/workbench/activity/detailActivity.do")
    public String detailActivity(String id,HttpServletRequest request) {
        //调用service方法，查询数据
        Activity activity = activityService.queryActivityForDetailById(id);
        List<ActivityRemark> activityRemarks = activityRemarkService.queryActivityReamrkForDetailByActivityId(id);
        //保存到request域中
        request.setAttribute("activity",activity);
        request.setAttribute("activityRemarks",activityRemarks);
        return "workbench/activity/detail";
    }

    //通过反射机制，生成excel行和列
    public static void getCell(HSSFRow row,HSSFCell cell,Activity activity)  {
        try {
            Field[] fields = activity.getClass().getDeclaredFields();
            int i = 0;
            boolean flag = true;
            String value = "";
            for(Field field : fields) {
                field.setAccessible(true);
                if(field.get(activity) == null) {
                    if(flag) {
                        value  = field.getName();
                    }else {
                       value = "";
                    }
                }else {
                    flag = false;
                    value = field.get(activity).toString();
                }
                cell = row.createCell(i++);
                cell.setCellValue(value);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
